package com.gugee.tiktok.web.spider;

import com.xiguaji.boot.retry.RetryableException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

@Component
public class BloggerSpiderClient {
    @Autowired
    RestTemplate restTemplate;

    @Value("${xiguaji.spider.host}")
    String host;

    @Retryable(value = RetryableException.class, maxAttempts = 10)
    public DiscoverBloggerResponse discover(String keyword){
        String uri = host + "/Aweme/DiscoverSearch?keyword={keyword}";
        ResponseEntity<DiscoverBloggerResponse> responseEntity =  restTemplate.getForEntity(uri, DiscoverBloggerResponse.class,keyword);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException(String.format("search blogger error. status: %s . msg: %s", responseEntity.getStatusCodeValue(), responseEntity.getBody()));
        }

        if (responseEntity.getBody() == null || responseEntity.getBody().getStatus_code() == 3071) {

            throw new RuntimeException("search blogger error");
        }

        return responseEntity.getBody();
    }

    @Retryable(value = RetryableException.class, maxAttempts = 10)
    public GetBloggerResponse get(Long uid, String region) {
        String uri = host + "/aweme/UserProfileFromUid?user_id={user_id}&region={region}";
        if (StringUtils.isEmpty(region)) {
            region = "US";
        }

        ResponseEntity<GetBloggerResponse> responseEntity = restTemplate.getForEntity(uri, GetBloggerResponse.class, uid, region);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException(String.format("get blogger error. status: %s . msg: %s", responseEntity.getStatusCodeValue(), responseEntity.getBody()));
        }
        if (responseEntity.getBody() == null || responseEntity.getBody().getStatus_code() == 3071) {

            throw new RetryableException("get blogger error, retry times 10. uri:" +
                    uri.replace("{user_id}", uid.toString()).replace("{region}", region));
        }
        return responseEntity.getBody();
    }
}
